import * as types from '../mutations'

import http from '../../http'

const state = {
  vm: '',
  content_list: [],
  total: ''
}

const getters = {
  content_list: state => state.content_list
}

const mutations = {
  [types.SET_VM]: (state, payload) => {
    state.vm = payload.vm
  },
  [types.SET_PRODUCT_LIST]: (state, payload) => {
    state.content_list = payload
  },
}

const actions = {
  get_content({
    dispatch,
    commit,
    state
  },payload) {
    http('/api/config/query_content', {}, res => {
      commit('SET_PRODUCT_LIST', res.data)
    })
  },
  set_dele({
    dispatch,
    commit,
    state
  }, payload) {
    http('/api/config/del_content', {
      id: payload.id,
      isdel: payload.isdel
    }, function (res) {
      if (res.code === 0){
        dispatch('get_content')
      }
    })
  },
  upload({
    dispatch,
    commit,state
  }, payload) {
    state.vm.$axios.post("/api/config/create_content", payload.form, {
      headers: { "Content-Type": "multipart/form-data" }
    }).then((res) => {
      if(res.data.code === 0){
        state.vm.newVisible = false
        dispatch('get_content')
      }
    })
  },
  content_detail({
    dispatch,
    commit,state
  }, payload) {
    http('/api/config/content_detail', {id: state.vm.contentParams.id}, res => {
      if(res.code === 0) {
        for (var i in state.vm.contentParams) {
          if(i === 'img') {
            state.vm.contentParams[i] = res.object.content[i].split(',').map(function(url) {
              return {url: res.object.domin + url}
            })
          }else{
            state.vm.contentParams[i] = res.object.content[i]
          }
        }
        state.vm.newVisible = true
        state.vm.sfile = []
      }
    })
  },
  modify_content({
    state,
    commit,
    dispatch
  }, payload) {
    var form = new FormData()
    var params = Object.assign({}, state.vm.contentParams)
    state.vm.sfile.forEach(function (file, index) {
      form.append('file' + index, file)
    })
    params.img = params.img.map(function (img) {
      return img.url.split('.com/')[1]
    })
    for (var i in params) {
      form.append(i, params[i])
    }
    state.vm.$axios.post("/api/config/modify_content", form, {
      headers: { "Content-Type": "multipart/form-data" }
    }).then((res) => {
      if(res.data.code === 0){
        state.vm.$message.success(res.data.message)
      }else{
        state.vm.$message.error(res.data.message)
      }
        state.vm.newVisible = false
        state.vm.sfile = []
        dispatch('get_content')
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions

}
